import { useIntersectionObserver , useIntervalFn} from "@vueuse/core"
import { onMounted, ref } from "vue"

// 接收一个回调函数,返回一个ref引用
// 功能: 当ref引用的dom处于可见转态时,调用一次回调函数
export function useLazyData(fn: () => void) {
  const target = ref(null)
  // 当整个区块处于可见状态时, 才发ajax
  onMounted(() => {
    const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
      // console.log('新鲜好物', isIntersecting)
      // 可见
      if (isIntersecting) {
        // 发请求
       fn()

        // 停止监听
        stop()
      }
    })
  })
  return target
}


export function useCountDown() {
  const counter = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    if (counter.value === 0) {
      pause()
    } else {
      counter.value--
    }
  }, 1000, { immediate: false })

  const start = (num: number) => {
    counter.value = num
    resume()
  }
  return { counter, start }
}